package com.smart.module.car.service.impl;

import cn.hutool.db.Page;
import com.smart.common.dynamicquery.DynamicQuery;
import com.smart.common.model.PageBean;
import com.smart.common.model.Result;
import com.smart.common.util.DateUtils;
import com.smart.module.car.entity.CarParkLinkman;
import com.smart.module.car.repository.CarParkLinkmanRepository;
import com.smart.module.car.service.CarParkLinkmanService;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CarParkLinkmanServiceImpl implements CarParkLinkmanService {

    @Resource
    private DynamicQuery dynamicQuery;

    @Resource
    private CarParkLinkmanRepository carParkLinkmanRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result save(CarParkLinkman entity) {
        if (entity.getId() == null){
            entity.setGmtCreate(DateUtils.getTimestamp());
            entity.setGmtModified(DateUtils.getTimestamp());
        }else {
            entity.setGmtModified(DateUtils.getTimestamp());
        }
        carParkLinkmanRepository.saveAndFlush(entity);
        return Result.ok("保存联系人成功");
    }

    @Override
    public Result list(CarParkLinkman entity) {
        String nativeSql = "select count(id) from app_car_park_linkman";
        nativeSql += common(entity);
        Long count = dynamicQuery.nativeQueryCount(nativeSql);
        PageBean<CarParkLinkman> data = new PageBean<>();
        if (count > 0){
            nativeSql = "SELECT * FROM app_car_park_linkman ";
            nativeSql += common(entity);
            nativeSql += "ORDER BY gmt_create desc";
            Pageable pageable = PageRequest.of(entity.getPageNo(),entity.getPageSize());
            List<CarParkLinkman> list = dynamicQuery.nativeQueryPagingList(CarParkLinkman.class, pageable, nativeSql);
            data = new PageBean<>(list,count);
        }
        return Result.ok(data);
    }

    public String common(CarParkLinkman entity){
        String name = entity.getName();
        String commonSql = " WHERE 1=1 ";
        if (StringUtils.hasLength(name)){
            commonSql += " AND name like '%" + name + "%' ";
        }
        String phone = entity.getPhone();
        if (StringUtils.hasLength(phone)) {
            commonSql += " AND phone like '%" + phone + "%' ";
        }
        return commonSql;
    }
}
